﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.ServiceProcess;
using Microsoft.Win32;
using System.Collections;
using System.Net;

namespace Shine.Util.Management
{
    /// <summary>
    /// 操作系统类
    /// </summary>
    public class OSHelper
    {
        /// <summary>
        /// 本机的IP地址
        /// </summary>
        private static List<string> _IPs = null;

        /// <summary>
        /// 获取本机的IP地址
        /// </summary>
        public static List<string> IPs
        {
            get
            {
                if (_IPs == null) _IPs = GetIPs();
                return _IPs;
            }
        }

        /// <summary>
        /// 判断操作系统是32位还是64位
        /// </summary>
        private static int _OSBit = 0;
        /// <summary>
        /// 判断操作系统是32位还是64位
        /// </summary>
        /// <returns></returns>
        public static int GetOSBit()
        {
            if (_OSBit != 0) return _OSBit;
            string addressWidth = String.Empty;
            ConnectionOptions mConnOption = new ConnectionOptions();
            ManagementScope mMs = new ManagementScope(@"\\localhost", mConnOption);
            ObjectQuery mQuery = new ObjectQuery("select AddressWidth from Win32_Processor");
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(mMs, mQuery);
            ManagementObjectCollection mObjectCollection = mSearcher.Get();
            foreach (ManagementObject mObject in mObjectCollection)
            {
                addressWidth = mObject["AddressWidth"].ToString();
            }
            _OSBit = Int32.Parse(addressWidth);
            return _OSBit;
        }

        /// <summary>
        /// 是否已安装ArcGIS Engine 10.1
        /// </summary>
        /// <returns></returns>
        public static bool CheckEngine101()
        {
            string wow = "";
            if ((GetOSBit() == 64)) wow = "Wow6432Node\\";
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey esrirk = rk.OpenSubKey("SOFTWARE\\" + wow + "ESRI\\Engine10.1\\CoreRuntime");
            if (esrirk == null) return false;
            object value = esrirk.GetValue("RealVersion");
            if (value == null || value.ToString().StartsWith("10.1") == false) return false;
            return true;
        }

        /// <summary>
        /// 是否已安装ArcGIS Desktop 10.1
        /// </summary>
        /// <returns></returns>
        public static bool CheckDesktop101()
        {
            string wow = "";
            if ((GetOSBit() == 64)) wow = "Wow6432Node\\";
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey esrirk = rk.OpenSubKey("SOFTWARE\\" + wow + "ESRI\\Desktop10.1\\CoreRuntime");
            if (esrirk == null) return false;
            object value = esrirk.GetValue("RealVersion");
            if (value == null || value.ToString().StartsWith("10.1") == false) return false;
            return true;
        }

        /// <summary>
        /// 验证Oracle 数据库是否安装正确
        /// </summary>
        /// <returns></returns>
        public static bool CheckOracle()
        {
            string wow = "";
            if ((GetOSBit() == 64)) wow = "Wow6432Node\\";
            RegistryKey rk = Registry.LocalMachine;
            RegistryKey oraclerk = rk.OpenSubKey("SOFTWARE\\" + wow + "Oracle");
            if (oraclerk == null) return false;
            return true;
        }

        /// <summary>
        /// 检查是否已安装CAD
        /// </summary>
        /// <param name="exePath">安装路径</param>
        /// <returns></returns>
        public static bool CheckCAD(out string exePath)
        {
            exePath = "";
            string strKey = "SOFTWARE\\Autodesk\\AutoCAD";
            Microsoft.Win32.RegistryKey pRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(strKey, false);
            if (pRegKey == null) return false;
            string[] strSubKeys = pRegKey.GetSubKeyNames();
            if (strSubKeys.Length == 0) return false;
            for (int i = 0; i < strSubKeys.Length; i++)
            {
                if (strSubKeys[i].Trim().ToUpper().StartsWith("R"))
                {
                    string strVersion = strSubKeys[i].Trim().ToUpper().Remove(0, 1);
                    double version;
                    if (double.TryParse(strVersion, out version))
                    {
                        if (version >= 17)
                        {
                            RegistryKey pSubKey = pRegKey.OpenSubKey(strSubKeys[i]);
                            if (pSubKey.SubKeyCount == 0) break;
                            RegistryKey pSubSubKey = pSubKey.OpenSubKey(pSubKey.GetSubKeyNames()[0]);
                            exePath = pSubSubKey.GetValue("Location").ToString() + "\\acad.exe";
                            if (System.IO.File.Exists(exePath)) return true;
                        }
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 检查是否已安装Excel
        /// </summary>
        /// <param name="exePath">安装路径</param>
        /// <returns></returns>
        public static bool CheckExcel(out string exePath)
        {
            exePath = "";
            string strKey = "SOFTWARE\\Microsoft\\Office";
            Microsoft.Win32.RegistryKey pRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(strKey, false);
            if (pRegKey == null) return false;
            string[] strSubKeys = pRegKey.GetSubKeyNames();
            if (strSubKeys.Length == 0) return false;
            for (int i = 0; i < strSubKeys.Length; i++)
            {
                double version;
                if (double.TryParse(strSubKeys[i], out version))
                {
                    if (version >= 11)
                    {
                        strKey = "SOFTWARE\\Microsoft\\Office\\" + strSubKeys[i] + "\\Excel\\InstallRoot";
                        pRegKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(strKey, false);
                        if (pRegKey != null)
                        {
                            string path = pRegKey.GetValue("Path").ToString();
                            string strExePath2 = path + "\\Excel.exe";
                            if (System.IO.File.Exists(strExePath2))
                            {
                                exePath = strExePath2;
                                return true;
                            }
                        }
                    }
                }

            }
            return true;
        }

        /// <summary>
        /// 启动Windows服务,若已启动，则直接返回
        /// Web.Config 配置文件：system.web  identity impersonate="true" userName="服务器登录名" password="登录密码"
        /// </summary>
        /// <param name="name">服务名称</param>
        public static void StartService(string name)
        {
            ServiceController service = new ServiceController(name);
            if (service.Status == ServiceControllerStatus.Running) return;
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
        }

        /// <summary>
        /// 启动Windows服务,若已启动，则停止后再启动
        /// </summary>
        /// <param name="name">服务名称</param>
        public static void ReStartService(string name)
        {
            ServiceController service = new ServiceController(name);
            if (service.Status == ServiceControllerStatus.Running)
            {
                service.Stop();
                service.WaitForStatus(ServiceControllerStatus.Stopped);
            }
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
        }

        /// <summary>
        /// 获取所有地址，包括IPv4和IPv6   
        /// </summary>
        /// <returns></returns>
        public static List<string> GetIPs()
        {
            List<string> ips = new List<string>();
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in addressList)
            {
                ips.Add(ip.ToString());
            }
            return ips;
        }

        /// <summary>
        /// 获取所有地址，包括IPv4和IPv6   
        /// </summary>
        /// <returns></returns>
        public static string GetIP()
        {
            System.Net.IPAddress[] addressList = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ip in addressList)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) return ip.ToString();
            }
            return "";
        }

        /// <summary>
        /// 判断
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsLocalIP(string ip)
        {
            if ("localhost".Equals(ip, StringComparison.CurrentCultureIgnoreCase)) return true;
            else if ("127.0.0.1".Equals(ip)) return true;
            else return IPs.Contains(ip);
        }

        /// <summary>
        /// 获取网卡的MAC地址
        /// </summary>
        public static string GetMac()
        {
            string strMac = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            int count = moc.Count;
            string strMacVmware = "";
            foreach (ManagementObject mo in moc)
            {

                if ((bool)mo["IPEnabled"] == true)
                {
                    string strCaption = mo["Caption"].ToString();
                    if (strCaption.ToLower().Contains("vmware"))
                    {
                        strMacVmware = mo["MacAddress"].ToString().Replace(":", "");
                        continue;
                    }
                    strMac = mo["MacAddress"].ToString().Replace(":", "");
                    break;
                }
            }
            if (strMac == "") return strMacVmware;
            return strMac;
        }
    }
}
